import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { SAMPLE_RATE, CHANNELS, FRAME_SIZE, OUTPUT_DIR } from './config.js';

// 使用导入的配置作为默认值
let currentSampleRate = SAMPLE_RATE;
let currentChannels = CHANNELS;
let currentOutputDir = OUTPUT_DIR;

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const queue = [];
let isWriting = false;
let shouldExit = false;

function makeOpusFileBuffer(frames) {
  // 动态检测帧大小
  let detectedFrameSize = FRAME_SIZE;
  if (frames.length > 0) {
    // 分析第一个帧来确定实际的帧大小
    const firstFrame = frames[0];
    if (firstFrame.length >= 1) {
      const firstByte = firstFrame[0];
      // 正确的OPUS TOC字节解析：config在bit 3-7，帧类型在bit 0-1
      const config = (firstByte >> 3) & 0x1F;
      const frameType = firstByte & 0x3;
      
      // 根据OPUS规范，帧大小由config决定
      // config 0-3: 2.5ms, 5ms, 10ms, 20ms
      // config 4-7: 40ms, 60ms, 80ms, 100ms  
      // config 8-11: 120ms, 140ms, 160ms, 180ms
      // config 12-15: 200ms, 220ms, 240ms, 260ms
      // config 16-19: 280ms, 300ms, 320ms, 340ms
      // config 20-23: 360ms, 380ms, 400ms, 420ms
      // config 24-27: 440ms, 460ms, 480ms, 500ms
      // config 28-31: 520ms, 540ms, 560ms, 580ms
      
      const frameSizes = [
        40, 80, 160, 320,   // config 0-3: 2.5ms, 5ms, 10ms, 20ms
        640, 960, 1280, 1600,  // config 4-7: 40ms, 60ms, 80ms, 100ms
        1920, 2240, 2560, 2880,  // config 8-11: 120ms, 140ms, 160ms, 180ms
        3200, 3520, 3840, 4160,  // config 12-15: 200ms, 220ms, 240ms, 260ms
        4480, 4800, 5120, 5440,  // config 16-19: 280ms, 300ms, 320ms, 340ms
        5760, 6080, 6400, 6720,  // config 20-23: 360ms, 380ms, 400ms, 420ms
        7040, 7360, 7680, 8000,  // config 24-27: 440ms, 460ms, 480ms, 500ms
        8320, 8640, 8960, 9280   // config 28-31: 520ms, 540ms, 560ms, 580ms
      ];
      
      if (config < frameSizes.length) {
        detectedFrameSize = frameSizes[config];
        console.log(`检测到OPUS帧大小: ${detectedFrameSize} 样本 (配置: ${config}, 帧类型: ${frameType})`);
      } else {
        console.log(`未知的OPUS配置: ${config}, 使用默认帧大小: ${detectedFrameSize}`);
      }
    }
  }
  
  // 头部: "OpusHead"(8) + version(1) + channels(1) + preSkip(2) + sampleRate(4) + gain(2) + mapping(1) = 19
  // 自定义扩展: frameSize(2) + totalFrames(4) = 6
  const header = Buffer.alloc(19 + 6);
  header.write('OpusHead', 0, 'ascii');
  header[8] = 1;
  header[9] = currentChannels & 0xFF;
  const preSkip = Math.floor(currentSampleRate * 0.08);
  header.writeUInt16LE(preSkip, 10);
  header.writeUInt32LE(currentSampleRate, 12);
  header.writeUInt16LE(0, 16);
  header[18] = 0;
  header.writeUInt16LE(detectedFrameSize, 19); // 使用检测到的帧大小
  header.writeUInt32LE(frames.length >>> 0, 21);

  const parts = [header];
  for (const f of frames) {
    const buf = Buffer.isBuffer(f) ? f : Buffer.from(f?.data || f);
    // 修改：使用4字节长度前缀，与客户端期望的格式保持一致
    const len = Buffer.alloc(4);
    len.writeUInt32LE(buf.length >>> 0, 0);
    parts.push(len, buf);
  }
  return Buffer.concat(parts);
}

async function processQueue() {
  if (isWriting) return;
  isWriting = true;
  while (queue.length > 0) {
    const item = queue.shift();
    const filepath = path.join(currentOutputDir, item.name);
    try {
      if (item.type === 'opus_segment') {
        const fileBuf = makeOpusFileBuffer(item.frames);
        const out = filepath.endsWith('.opus') ? filepath : filepath + '.opus';
        
        // 确保输出目录存在
        const outDir = path.dirname(out);
        if (!fs.existsSync(outDir)) {
          fs.mkdirSync(outDir, { recursive: true });
        }
        
        await fs.promises.writeFile(out, fileBuf);
        console.log('已保存文件:', out);
      }
    } catch (e) {
      process.send?.({ type: 'error', message: e?.message || String(e) });
    }
  }
  isWriting = false;
  if (shouldExit) {
    process.send?.({ type: 'exited' });
    process.exit(0);
  }
}

process.on('message', (msg) => {
  if (!msg || typeof msg !== 'object') return;
  if (msg.type === 'init') {
    const cfg = msg.config || {};
    currentSampleRate = cfg.sampleRate || currentSampleRate;
    currentChannels = cfg.channels || currentChannels;
    currentOutputDir = cfg.outputDir || currentOutputDir;
    
    // 确保输出目录存在
    if (!fs.existsSync(currentOutputDir)) {
      fs.mkdirSync(currentOutputDir, { recursive: true });
    }
    
    process.send?.({ type: 'ready' });
  } else if (msg.type === 'opus_segment' && Array.isArray(msg.frames) && msg.frames.length > 0 && msg.name) {
    const frames = msg.frames.map(f => (Buffer.isBuffer(f) ? f : Buffer.from(f?.data || f)));
    queue.push({ type: 'opus_segment', frames, name: msg.name });
    processQueue();
  } else if (msg.type === 'exit') {
    shouldExit = true;
    if (!isWriting && queue.length === 0) {
      process.send?.({ type: 'exited' });
      process.exit(0);
    }
  }
});

process.send?.({ type: 'ready' });

process.on('SIGINT', () => {
  shouldExit = true;
  if (!isWriting && queue.length === 0) {
    process.send?.({ type: 'exited' });
    process.exit(0);
  }
});


